/*
 * Copyright (C),2015,北京新诺创科软件技术有限公司
 * author zhangmengliang
 */
package com.xnck.example.jertest.util;

import com.alibaba.fastjson.JSON;
import com.xiaoleilu.hutool.StrUtil;
import com.xnck.example.jertest.constant.ContextConstant;
import com.xnck.example.jertest.context.HttpContext;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * Response常用工具类
 * @author zhangmengliang
 *
 */
public class ResponseUtil {
	/**
	 * response输出字符串
	 */
	public static void responseString(String str) throws Exception {
		HttpServletResponse response = HttpContext.get().getResponse();
		responseString(response, str);
	}

    public static void responseJSON(Map<String, Object> map) throws Exception {
        HttpServletResponse response = HttpContext.get().getResponse();
        responseJSON(response, map);
    }

    /**
     * 封装并以json返回成功执行的信息
     */
    public static void responseSuccessMsg(Object data, String msg) throws Exception {
        HttpServletResponse response = HttpContext.get().getResponse();
        responseSuccessMsg(response, data, msg);
    }

    /**
     * 封装并以json返回错误执行的信息
     */
    public static void responseErrorMsg(String msg) {
        HttpServletResponse response = HttpContext.get().getResponse();
        responseErrorMsg(response, msg);
    }

    /**
     * 封装并以json返回身份认证失败执行的信息
     */
    public static void responseAuthFailedMsg(String msg) {
        HttpServletResponse response = HttpContext.get().getResponse();
        responseAuthFailedMsg(response, msg);
    }

    public static void responseString(HttpServletResponse response, String str) throws Exception {
        try {
            //设置页面不缓存
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out= response.getWriter();
            out.print(str);
            out.flush();
            out.close();
        } catch (Exception e) {
            throw e;
        }
    }

    public static void responseSuccessMsg(HttpServletResponse response, Object data, String msg) throws Exception {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            map.put(ContextConstant.KEY_DATA, data);
            map.put(ContextConstant.KEY_CODE, ContextConstant.VALUE_SUCCESS);
            map.put(ContextConstant.KEY_MSG, msg);
            responseJSON(response, map);
        } catch (Exception e) {
            throw e;
        }
    }

    public static void responseErrorMsg(HttpServletResponse response, String msg) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            map.put(ContextConstant.KEY_CODE, ContextConstant.VALUE_ERROR);
            map.put(ContextConstant.KEY_MSG, msg);
            responseJSON(response, map);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void responseAuthFailedMsg(HttpServletResponse response, String msg) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            map.put(ContextConstant.KEY_CODE, ContextConstant.VALUE_AUTHEN_FAILED);
            map.put(ContextConstant.KEY_MSG, msg);
            responseJSON(response, map);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void responseJSON(HttpServletResponse response, Map<String, Object> map) throws Exception {
        try {
            response.setContentType("application/json;charset=UTF-8");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setCharacterEncoding("utf-8");
            PrintWriter out= response.getWriter();
            out.print(JSON.toJSONString(map));
            out.flush();
            out.close();
        } catch (Exception e) {
            throw e;
        }
    }

    //region response file

    public static void responseFile(String fileName, String filePath) throws Exception {
        HttpServletResponse response = HttpContext.get().getResponse();
        responseFile(response, fileName, fileName, filePath);
    }

    public static void responseFile(String fileName, String physicFileName, String filePath) throws Exception {
        HttpServletResponse response = HttpContext.get().getResponse();
        responseFile(response, fileName, physicFileName, filePath);
    }

    public static void responseFile(HttpServletResponse response, String fileName, String physicFileName, String filePath) throws Exception {
        if (StrUtil.isBlank(fileName) || StrUtil.isBlank(filePath)) {
            throw new Exception("文件不存在");
        }
        String contentType = getContentType(physicFileName);
        if (StrUtil.isNotBlank(contentType)) {
            response.setContentType(contentType);
        }
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=\""+
                new String(fileName.getBytes("gb2312"), "ISO8859-1" )+"\"");
        try {
            InputStream inputStream = new FileInputStream(new File(filePath + physicFileName));
            OutputStream os = response.getOutputStream();
            byte[] b = new byte[2048];
            int length;
            while ((length = inputStream.read(b)) > 0) {
                os.write(b, 0, length);
            }
            os.close();
            inputStream.close();
        } catch (Exception e){
            throw e;
        }
    }

    private static String getContentType(String fileName){
        String contentType;
        String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        if (suffixName.equals("doc") || suffixName.endsWith("docx")) {
            contentType = "application/msword";
        }
        else if (suffixName.equals("xls") || suffixName.endsWith("xlsx")) {
            contentType = "application/vnd.ms-excel";
        }
        else if (suffixName.equals("pdf")) {
            contentType = "application/pdf";
        }
        else if (suffixName.equals("ppt")) {
            contentType = "appication/powerpoint";
        }
        else if (suffixName.equals("jpeg") || suffixName.endsWith("jpg") || suffixName.endsWith("jpe")) {
            contentType = "image/jpeg";
        }
        else {
            contentType = "application/octet-stream";
        }
        return contentType;
    }

    //endregion
}
